<script lang="ts">
  import { onMount } from 'svelte';
  import { checkHealth } from '../lib/api';
  import UploadForm from '../components/UploadForm.svelte';
  import { t } from '../lib/i18n';
  
  let healthStatus = $t('common.loading') as string;
  let isServerOnline = false;
  let isChecking = false;
  let retryCount = 0;
  const MAX_RETRIES = 2;
  let errorDetails = '';
  
  async function checkServerHealth() {
    if (isChecking) return;
    
    isChecking = true;
    try {
      const health = await checkHealth();
      healthStatus = $t('upload.status.online', { version: health.version }) as string;
      isServerOnline = true;
      retryCount = 0;
      errorDetails = '';
    } catch (error: any) {
      console.error('服务器健康检查失败:', error);
      healthStatus = $t('upload.status.offline') as string;
      isServerOnline = false;
      errorDetails = error.message || '未知错误';
      
      // 如果没有超过最大重试次数，等待后重试
      if (retryCount < MAX_RETRIES) {
        retryCount++;
        setTimeout(() => {
          isChecking = false;
          checkServerHealth();
        }, 2000); // 2秒后重试
      }
    } finally {
      isChecking = false;
    }
  }
  
  onMount(() => {
    checkServerHealth();
  });
  
  function retryConnection() {
    retryCount = 0;
    checkServerHealth();
  }
</script>

<svelte:head>
  <title>{$t('app.title')}</title>
</svelte:head>

<div class="container">
  <header>
    <p class="status">
      {$t('upload.status.label')}: 
      <span class={isServerOnline ? 'online' : 'offline'}>
        {healthStatus}
      </span>
      {#if !isServerOnline}
        <button class="retry-button" on:click={retryConnection} disabled={isChecking}>
          {isChecking ? '重试中...' : $t('common.retry')}
        </button>
        {#if errorDetails}
          <span class="error-tooltip" title={errorDetails}>
            <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
              <circle cx="12" cy="12" r="10"></circle>
              <line x1="12" y1="8" x2="12" y2="12"></line>
              <line x1="12" y1="16" x2="12.01" y2="16"></line>
            </svg>
          </span>
        {/if}
      {/if}
    </p>
  </header>
  
  <main>
    <div class="intro">
      <p>
        {$t('upload.description')}
      </p>
    </div>
    
    {#if isServerOnline}
      <UploadForm />
    {:else}
      <div class="error-message">
        <p>{$t('upload.errors.server_offline')}</p>
        <div class="error-details">
          <p>可能的原因:</p>
          <ul>
            <li>后端服务器未运行 (请确认端口5000的服务器正在运行)</li>
            <li>网络连接问题</li>
            <li>CORS配置错误</li>
            <li>代理配置不正确</li>
          </ul>
          <p>错误详情: {errorDetails || '未知错误'}</p>
        </div>
        <div class="error-actions">
          <button on:click={retryConnection} disabled={isChecking}>
            {isChecking ? '重试中...' : $t('common.retry')}
          </button>
          <a href="/debug" class="debug-link">使用调试工具</a>
        </div>
      </div>
    {/if}
  </main>
  
  <footer>
    <p>{$t('app.copyright')}</p>
  </footer>
</div>

<style>
  .container {
    max-width: 1200px;
    margin: 0 auto;
    padding: 2rem;
    font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen,
      Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;
  }
  
  header {
    margin-bottom: 2rem;
    border-bottom: 1px solid #eee;
    padding-bottom: 1rem;
  }
  
  .status {
    font-size: 0.9rem;
    color: #666;
    display: flex;
    align-items: center;
    gap: 0.5rem;
  }
  
  .retry-button {
    background: none;
    border: none;
    color: #4a90e2;
    cursor: pointer;
    font-size: 0.9rem;
    text-decoration: underline;
    padding: 0;
  }
  
  .retry-button:disabled {
    opacity: 0.5;
    cursor: wait;
  }
  
  .error-tooltip {
    color: #e53935;
    display: inline-flex;
    align-items: center;
    cursor: help;
  }
  
  .online {
    color: green;
    font-weight: bold;
  }
  
  .offline {
    color: red;
    font-weight: bold;
  }
  
  main {
    background-color: #f9f9f9;
    border-radius: 8px;
    padding: 2rem;
    margin-bottom: 2rem;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  }
  
  .intro {
    margin-bottom: 2rem;
  }
  
  .error-message {
    background-color: #fff3f3;
    border: 1px solid #ffcfcf;
    padding: 1rem;
    border-radius: 4px;
    margin-top: 1rem;
  }
  
  .error-details {
    margin: 1rem 0;
    font-size: 0.9rem;
    color: #555;
    border-left: 3px solid #ffcfcf;
    padding-left: 1rem;
  }
  
  .error-details ul {
    margin: 0.5rem 0;
    padding-left: 1.5rem;
  }
  
  .error-actions {
    display: flex;
    gap: 1rem;
    margin-top: 1rem;
    justify-content: center;
  }
  
  .error-message button {
    background-color: #4a90e2;
    color: white;
    border: none;
    padding: 0.5rem 1rem;
    border-radius: 4px;
    cursor: pointer;
    font-size: 0.9rem;
  }
  
  .error-message button:disabled {
    opacity: 0.5;
    cursor: wait;
  }
  
  .debug-link {
    display: inline-block;
    padding: 0.5rem 1rem;
    border: 1px solid #4a90e2;
    color: #4a90e2;
    text-decoration: none;
    border-radius: 4px;
    font-size: 0.9rem;
  }
  
  .debug-link:hover {
    background-color: #f0f7ff;
  }
  
  footer {
    text-align: center;
    color: #888;
    font-size: 0.8rem;
  }
</style>
